<?php
namespace api\modules\v1\controllers\trade;
use Yii;
use api\modules\v1\controllers\CoreController;
use common\models\trade\TradeGoodsModel;
use common\models\trade\TradeOrderModel;
use common\bonus\BaseBonus;
use api\modules\models\finance\Balance;
use common\models\finance\StaticInstanceModel;
use common\models\finance\StaticInstanceOrderModel;
use api\modules\models\member\Member;
/*
	投资
*/

class InvestController extends CoreController
{

	## 投资配置文件
	public function actionInvest_conf()
	{
		$data = TradeGoodsModel::find()->where(['mch_id'=>MCHID,'type'=>'invest'])->asarray()->all();
		$extend = ['balance'=>0];
		if($data){
			$conf = $data[0];
			$bInfo = Balance::getBalance($this->_memberId,$conf['btype']);
			$extend['balance'] = $bInfo['balance'];
			$extend['type_name'] = $bInfo['type_name'];
			if($this->request('lang')=='en') $extend['type_name'] = Balance::$typeNameEn[$conf['btype']];
		}
		$this->out('投资配置信息',$data,$extend);
	}

	/* 
		投资
		* goods_id  投资的id
		* password  密码
	*/
	public function actionAdd_invest()
	{
		if(!$goodsId = $this->request('goods_id')) $this->error('参数有误');
		$conf = TradeGoodsModel::find()->where(['goods_id'=>$goodsId])->asarray()->one();
		if(!$conf) $this->error('配置信息有误');

		if($this->_member['paypwd'] !== md5($this->request('password'))) $this->error('密码有误');

		$order = TradeOrderModel::find()
				->where(['member_id'=>$this->_memberId,'order_type'=>'invest'])
				->orderBy('amount desc')
				->asarray()->one();
		$investNum = isset($order['amount'])?$order['amount']:0;
		if($conf['value']<$investNum) $this->error('挖矿数量需要大于等于'.$investNum);

		try{
			$transaction = Yii::$app->db->beginTransaction();

			//创建订单
			if(!$orderId = $this->createTradeOrder($conf)) throw new \Exception("订单创建失败");
			
			//扣除账本
			$res = Balance::reduceBalance($this->_memberId,$conf['btype'],$conf['value'],7,$orderId);
			if(!$res['state']) throw new \Exception($res['msg']);

			
			$transaction->commit();

			//触发后续
			$params = array();
			$params['money'] = $conf['value'];
			$params['member_id'] = $this->_memberId;
			$params['source_id'] = $orderId;
			$params['mch_id'] = MCHID;
			$params['trigger_type'] = 1;
			$params['desc'] = 'from 【'.$this->_member['member_name'].'】';
			BaseBonus::bonusRun($params);
			$this->out('操作成功');

		}catch(\Exception $e)
		{
			$transaction->rollback();
			$this->error($e->getMessage());
		}
	}


	private function createTradeOrder($conf)
	{
		$data = array();
		$data['mch_id'] = 1;//MCHID;
		$data['member_id'] = $this->_memberId;
		$data['invite_id'] = $this->_member['invite_id'];
		$data['btype'] = $conf['btype'];
		$data['order_type'] = $conf['type'];
		$data['goods_id'] = $conf['goods_id'];
		$data['amount'] = $conf['value'];
		$data['create_time'] = time();
		$data['update_time'] = time();
		$model = new TradeOrderModel;
		if($model->load($data,'') && $model->save()){
			return Yii::$app->db->getLastInsertID();
		}
		return false;
	}


	## 投资列表
	public function actionInvest_list()
	{
		$whereArr = array();
		$whereArr['where'] = ['member_id'=>$this->_memberId];
		$params = array(
			'field' => ['*'],
			'page'	=> $this->request('page',1),
			'limit' => $this->request('page_size',10),
			'order' => 'id DESC'
		);
		$data = StaticInstanceModel::investList($whereArr,$params);
		foreach($data as &$val)
		{
			$val['state_text'] = $val['status']=='1'?'收益中':'已完成';
		}

		$this->out('投资信息',$data);
	}


	/*
		投资详细订单列表
		* id
	*/
	public function actionInvest_detail()
	{
		if(!$id = $this->request('id')) $this->error('参数有误');

		$whereArr = array();
		$whereArr['where'] = ['instance_id'=>$id];
		$params = array(
			'field' => ['*'],
			'page'	=> $this->request('page',1),
			'limit' => $this->request('page_size',10),
			'order' => 'id DESC'
		);
		$data = StaticInstanceOrderModel::investOrderList($whereArr,$params);
		$typeText = array('1'=>'挖矿','2'=>'团队奖励');
		if($this->request('lang')=='en') $typeText = array('1'=>'Gig','2'=>'Team rewards');
		foreach($data as &$val)
		{
			$val['desc'] = $typeText[$val['type']];
			if($val['type']==2)
			{
				$member = Member::getMemberById($val['from_member_id'],['member_name','member_id','member_email']);
				if($this->request('lang')=='cn') $val['desc'] .= '('.$member['member_name'].'）挖矿';
				if($this->request('lang')=='en') $val['desc'] .= '('.$member['member_name'].'）Gig';
			}
		}
		$this->out('投资明细列表',$data);
	}


	

}


